package com.lwphk.easydocs.util;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

public class ClassTypeUtil {

	
	/**
	 * 是否基础类型或者包装类 , 或者是string   BigDecimal
	 * @param clz
	 * @return
	 */
	public static boolean isPrimitive(Class<?> clz) {
		try {
            return  BigDecimal.class == clz || String.class == clz  || clz.isPrimitive() || ((Class<?>) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            return false;
        }
	}
	
	public static boolean isMap(Class<?> c) {
		  return Map.class.isAssignableFrom(c);
	}
	
	
	public static boolean isCollection(Class<?> c) {
		  return  Collection.class.isAssignableFrom(c);
	}
	
	
	public static boolean isArray(Class<?> c) {
		return c.isArray();
	}
	
	
	public static boolean isArray(Field field) {
		return field.getType().isArray();
	}
	
	public static boolean isUpload(Parameter e) {
		Class<?> clazz = e.getType();
		if(clazz == MultipartFile.class) {
			return true;
		}
		if(clazz.isArray() && clazz.getComponentType() == MultipartFile.class){
			return true;
		}
		
		return false;
	}
	
	
	
	
	
	
	public static Class<?> getCollectionGenericType(Type type) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Type[] typeArguments = parameterizedType.getActualTypeArguments();
            if (typeArguments.length == 1) {
                return getCollectionGenericType(typeArguments[0]);
            } 
        } else if (type instanceof Class) {
        	Class<?> tc = (Class<?>) type;
        	if(tc.isArray()) return tc.getComponentType();
            return tc;
        }
        return null;
    }
	
	
	public static Class<?> getArrayGenericType(Type type) {
		if (type instanceof Class) {
	        Class<?> clazz = (Class<?>) type;
	        return clazz.getComponentType();
	    } else if (type instanceof GenericArrayType) {
	        GenericArrayType genericArrayType = (GenericArrayType) type;
	        Type componentType = genericArrayType.getGenericComponentType();
	        Class<?> componentClass = getArrayGenericType(componentType);
	        if (componentClass != null) {
	            return Array.newInstance(componentClass, 0).getClass();
	        }
	    }
	    return null;
    }
	
	
}


